package com.lebang.controller.api.member;

import com.alibaba.fastjson.JSONObject;
import com.lebang.aop.Sessionid;
import com.lebang.common.Require;
import com.lebang.component.RedisClient;
import com.lebang.domain.LbbMemberIsfirstinfo;
import com.lebang.domain.PromotionRewardSetting;
import com.lebang.entity.LbbDict;
import com.lebang.entity.RequestHeaders;
import com.lebang.entity.member.LbbMember;
import com.lebang.entity.member.LbbMemberInviteDetail;
import com.lebang.entity.member.TbMemberInviteStatistics;
import com.lebang.model.MoneyCategory;
import com.lebang.model.Whether;
import com.lebang.model.enums.InviteEnum;
import com.lebang.model.enums.buss.TaskCategory;
import com.lebang.service.MemberInviteRebateRecordService;
import com.lebang.service.MemberNoticeService;
import com.lebang.service.buss.*;
import com.lebang.service.setting.PromotionRewardService;
import com.lebang.service.sys.DictService;
import com.lebangweb.common.TextUtil;
import com.lebangweb.common.UUIDUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * @author : szq
 * @Date: 2019-16 15:54
 * @Description:
 */
@RequestMapping("/toinvite")
@Controller
public class MemberInviteApi {

    @Autowired
    private MemberInviteStatisticsService memberInviteStatisticsService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberInviteDetailService memberInviteDetailService;
    @Autowired
    private MemberIsFirstInfoService memberIsFirstInfoService;

    @Autowired
    private WalletService walletService;
    @Autowired
    private PromotionRewardService promotionRewardService;
    @Autowired
    private DictService dictService;
    @Autowired
    private MemberInviteRebateRecordService memberInviteRebateRecordService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private MemberTradeService memberTradeService;
    @Autowired
    private MemberNoticeService memberNoticeService;

    public Boolean checkNumber(String memberId) {

        int num = Integer.parseInt(dictService.selectByKeyName("rebate_numbers").getKeyvalue());
        TbMemberInviteStatistics memberInviteStatistics = memberInviteStatisticsService.getByMemberId(memberId);
        if (memberInviteStatistics != null) {
            if (memberInviteStatistics.getNumbers() >= num) {
                //判断该用户的徒弟是否有提现过
                int count = walletService.checkincome(memberId);
                if ((memberInviteStatistics.getNumbers() - count) >= num) {
                    return false;
                }
            }
        }
        return true;
    }

    private static int getNum(int start, int end) {
        return (int) (Math.random() * (end - start + 1) + start);
    }

    private String getRandomChar() {
        String[] chars = new String[]{"ぇ", "え", "ぉ", "お", "が", "い", "い", "Э", "Δ", "／", "〃", "∵", "ガ", "ぺ", "デ", "フ", "ヲ"};
        String s = chars[getNum(0, chars.length - 1)] + chars[getNum(0, chars.length - 1)];
        return s;
    }

    /**
     * 进入 邀请 页面
     *
     * @return
     */
    @RequestMapping(value = "/invite", method = {RequestMethod.POST})
    @ResponseBody
    @Require
    @Sessionid
    public JsonData invite(HttpServletRequest request) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        String memberId = requestHeaders.getUserid();
        LbbMember member = memberService.getMemberByMemberId(memberId);
        String inviteCode = member.getInviteCode();
        Boolean flag = this.checkNumber(memberId);
        if (!flag) {
            return Callback.fail("201", "请先帮助徒弟完成提现再继续邀请!");
        }
        String str = "";
        str = redisClient.get("XIANYU_YAOXIN_URL");
        if (str == null) {
            LbbDict web = dictService.selectByKeyName("wangzhi");
            str = "[机智]" + dictService.selectByKeyName("dianji").getKeyvalue() + "[" + web.getKeyvalue() + "]\n" +
                    "[耶]" + dictService.selectByKeyName("app").getKeyvalue() + getRandomChar() + "\n" +
                    "\uD83D\uDCB0" + dictService.selectByKeyName("work").getKeyvalue() + getRandomChar() + "\n" +
                    "[红包]" + dictService.selectByKeyName("hongbao").getKeyvalue() + getRandomChar() + "\n" +
                    "\uD83D\uDE0F" + dictService.selectByKeyName("invitecode").getKeyvalue() + "【" + "{inviteCode}" + "】" + getRandomChar() + "\n" +
                    dictService.selectByKeyName("fuzhi").getKeyvalue() + getRandomChar();
            redisClient.set("XIANYU_YAOXIN_URL", str);
        }
        str = str.replace("{inviteCode}", inviteCode);
        return Callback.success("200", "", str);
    }


    /**
     * 获取邀请基本信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/info", method = RequestMethod.POST)
    @ResponseBody
    @Require
    @Sessionid
    public JsonData getInviteInfo(HttpServletRequest request) {
        try {
            RequestHeaders requestHeaders = new RequestHeaders(request);
            String memberId = requestHeaders.getUserid();
            String appid = requestHeaders.getAppid();
            LbbMember member = memberService.getMemberByMemberId(memberId);
            //今日收徒数量
            LocalDate now = LocalDate.now();
            LocalDateTime min = LocalDateTime.of(now, LocalTime.MIN);
            LocalDateTime max = LocalDateTime.of(now, LocalTime.MAX);

            //判断是否是第一次进入新手页面引导
            JSONObject memberJson = new JSONObject();
            memberJson.put("sf_rebate", dictService.selectByKeyName("sf_rebate").getKeyvalue());
            memberJson.put("td_rebate", dictService.selectByKeyName("td_rebate").getKeyvalue());

            //一个徒弟/徒孙可给师傅带来的最高收益
            memberJson.put("sfMax", dictService.selectByKeyName("td_max").getKeyvalue());
            memberJson.put("tdMax", dictService.selectByKeyName("ts_max").getKeyvalue());
            LbbMemberIsfirstinfo lbbMemberIsfirstinfo = memberIsFirstInfoService.selectByid(memberId);
            boolean flag = memberService.checkTimeOut(memberId);
            if (flag && lbbMemberIsfirstinfo == null) {
                LbbMemberIsfirstinfo memberIsfirstinfo = new LbbMemberIsfirstinfo();
                memberIsfirstinfo.setCreateTime(LocalDateTime.now());
                memberIsfirstinfo.setIsFirstinfo(1);
                memberIsfirstinfo.setMemberId(memberId);
                memberIsFirstInfoService.insertByid(memberIsfirstinfo);
                return Callback.success("201", "进入新手引导页面", memberJson);
            }
            memberJson.put("nickname", TextUtil.isEmpty(member.getNickname()) ? member.getPhone() : member.getNickname());
            memberJson.put("inviteCode", member.getInviteCode());
            //累计所有收入
            memberJson.put("allmoney", new BigDecimal(walletService.totalMoney(memberId, appid)).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN));
            TbMemberInviteStatistics memberInviteStatistics = memberInviteStatisticsService.getByMemberId(memberId);
            if (memberInviteStatistics == null) {
                memberJson.put("todaynumbers", 0);
                memberJson.put("todaymoney", 0.0);
                memberJson.put("numbers", 0);
                memberJson.put("totalMoney", 0.0);
                memberJson.put("tsnumbers",0);
                memberJson.put("totaltdmoney",0.0);
                memberJson.put("totaltsmoney",0.0);
                memberJson.put("todaytdmoney",0.0);
                memberJson.put("todaytsmoney",0.0);
            } else {
                int todayNumber = memberService.getCountByMemberId(memberId, min, max);
                memberJson.put("todaynumbers", todayNumber);
                //今日累计收益
                memberJson.put("todaymoney", new BigDecimal(memberInviteRebateRecordService.gettoday(memberId)).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN));
                //累计徒弟/徒孙总收益
                memberJson.put("totalMoney", new BigDecimal(memberInviteStatistics.getTotalMoney() + memberInviteStatistics.getTotalTsMoney()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN));
                //累计徒弟数量
                memberJson.put("numbers", memberInviteStatistics.getNumbers());
                //累计徒孙数量
                memberJson.put("tsNumbers",memberInviteStatisticsService.getTsNumbers(memberId));
                //徒弟累计收益
                memberJson.put("totalTdMoney",new BigDecimal(memberInviteStatistics.getTotalMoney()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN));
                //徒孙累计收益
                memberJson.put("totalTsMoney",new BigDecimal(memberInviteStatistics.getTotalTsMoney()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN));
                //今日徒弟收益
                memberJson.put("todayTdMoney", new BigDecimal(memberInviteRebateRecordService.getTodayMoney(memberId,0,min,max)).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN));
                //今日徒孙收益
                memberJson.put("todayTsMoney", new BigDecimal(memberInviteRebateRecordService.getTodayMoney(memberId,1,min,max)).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN));
            }
            JSONObject data = new JSONObject();
            data.put("member", memberJson);
            return Callback.success("200", "success", data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Callback.fail("403", "网络异常", "");
    }

    /**
     * 绑定师傅申请
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/band", method = RequestMethod.POST)
    @ResponseBody
    @Require
    @Sessionid
    public JsonData bandInvite(HttpServletRequest request, String inviteCode) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        String memberId = requestHeaders.getUserid();
        //当前用户判断
        LbbMember member = memberService.getMemberByMemberId(memberId);
        if (!TextUtil.isEmpty(member.getInviterId())) {
            return Callback.fail("201", "你已经绑定过，不能再绑定了");
        }
        //判断用户自己绑定自己
        if (member.getInviteCode().equalsIgnoreCase(inviteCode)) {
            return Callback.fail("201", "您不能绑定自己的验证码！");
        }
        LbbMember lbbMember = memberService.selectMemberByCode(inviteCode);
        if (lbbMember == null) {
            return Callback.fail("201", "绑定用户不存在，请重新绑定!");
        }
        if (lbbMember.getInviterId().equals(memberId)) {
            return Callback.fail("201", "对方已经是你的徒弟");
        }
        JSONObject memberJson = new JSONObject();
        memberJson.put("inviteCode", lbbMember.getInviteCode());
        memberJson.put("nickname", lbbMember.getNickname());

        return Callback.success("200", "", memberJson);

    }

    /**
     * 是否绑定确认
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/bandconfirm", method = RequestMethod.POST)
    @ResponseBody
    @Require
    @Sessionid
    public JsonData bandConfirm(HttpServletRequest request, String inviteCode) {
        RequestHeaders header=new RequestHeaders(request);
        String memberId = header.getUserid();
        String uuid = UUIDUtil.M();
        try {
            //师傅
            LbbMember lbbMember = memberService.selectMemberByCode(inviteCode);
            //加锁避免多个徒弟一起给师傅操作
            boolean lock = redisClient.tryGetDistributedLock("lock:bandConfirm:" + lbbMember.getMemberId(), uuid, 120 * 1000);
            if(!lock){
                return Callback.fail("211", "服务器繁忙,请重试");
            }

            //当前用户为徒弟
            LbbMember member = memberService.getMemberByMemberId(memberId);
            if (!TextUtil.isEmpty(member.getInviterId())) {
                return Callback.fail("201", "你已经绑定过，不能再绑定了");
            }
            if (lbbMember.getInviterId().endsWith(memberId)) {
                return Callback.fail("201", "不能互为师徒");
            }

            //师傅有徒弟后不能绑定
//            if (){
//
//            }
            Boolean flag = this.checkNumber(lbbMember.getMemberId());
            if (!flag) {
                return Callback.fail("201", "该师傅未提现徒弟太多，暂时无法绑定");
            }
            if(!memberInviteDetailService.checkBind(memberId)){
                return Callback.fail("201", "您已是师傅，无法获得师徒奖励");
            }
            //根据memberId查询是否有邀请绑定过的详情
            LbbMemberInviteDetail memberInviteDetail = memberInviteDetailService.getByMemberId(memberId);
            memberInviteStatisticsService.addNewMember(lbbMember.getMemberId(),header);
            if (memberInviteDetail == null) {
                memberInviteDetailService.insert(memberId, lbbMember.getMemberId());
                //不用判断时间,直接师徒奖励和消息通知
                memberInviteDetailService.rewordTask(memberId, lbbMember,header);
            } else {
                //判断是否超过24小时,
                long time = memberIsFirstInfoService.checkTime(memberId);
                if (time > 0) {
                    memberInviteDetailService.rewordTask(memberId, lbbMember,header);
                }
                //更改邀请详情表的enable=1
                memberInviteDetailService.updateEnableById(memberId, lbbMember.getMemberId());
            }
            memberService.updateInviteById(memberId, lbbMember.getMemberId(), InviteEnum.OLD_VERSION.getIndex());
            //判断师傅是否达到收徒人数达到对应人数时，可获对应奖励,可以就直接返利
            PromotionRewardSetting setting= promotionRewardService.checkReward(lbbMember);
            if(setting!=null){
                String desc="收徒人数达到"+setting.getNumbers()+"人数，获得"+new BigDecimal(setting.getMoney()).divide(new BigDecimal(100),2,BigDecimal.ROUND_DOWN) +"元奖励";
                memberTradeService.addMoney(lbbMember.getMemberId(), setting.getMoney(), "达到人数返利奖励", desc, "", header,
                        "", new MoneyCategory(Whether.NO, TaskCategory.MASTER));
                //计入累计收益
                memberInviteStatisticsService.addTotalAmount(lbbMember.getMemberId(), setting.getMoney(), 0);
                //师徒收益存入redis
                memberInviteRebateRecordService.settoday(lbbMember.getMemberId(), setting.getMoney());
                memberNoticeService.addNoticeAndPush("达到人数返利奖励", desc, memberId, header);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return Callback.fail("200", "绑定失败,请联系客服");
        } finally {
            redisClient.releaseDistributedLock("lock:bandConfirm:" + memberId, uuid);
        }
        return Callback.success("200", "绑定成功,1元已发放至余额");
    }

    /**
     * 我再考虑一下
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/thinkabout", method = RequestMethod.POST)
    @ResponseBody
    @Require
    @Sessionid
    public JsonData thinkAbout(HttpServletRequest request) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        String memberId = requestHeaders.getUserid();
        return Callback.success("200", "", memberIsFirstInfoService.checkTime(memberId));


    }

    /**
     * 获取倒计时时间
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/countdown", method = {RequestMethod.POST})
    @ResponseBody
    @Require
    @Sessionid
    public JsonData countdown(HttpServletRequest request) {
        RequestHeaders requestHeaders=new RequestHeaders(request);
        String memberId = requestHeaders.getUserid();
        LbbMember member = memberService.getMemberByMemberId(memberId);

        if (!TextUtil.isEmpty(member.getInviterId())) {
            return Callback.fail("201", "");
        }
        LbbMemberIsfirstinfo memberIsfirstinfo = memberIsFirstInfoService.selectByid(memberId);
        if (memberIsfirstinfo == null) {
            return Callback.fail("201", "");
        }
        return Callback.success("200", "", memberIsFirstInfoService.checkTime(memberId));

    }

}
